import { localstorageDao } from './../utils/localstorage';
import { Terminal } from './../models/terminal';
import { Devices, DeviceInfo, Device, Ads } from './../models/devices';
import { Injectable } from '@angular/core';
import { Http, Jsonp, URLSearchParams } from '@angular/http';
import { ServiceBase } from "./base";
import * as guid from 'uuid/v1';

@Injectable()
export class StoreSvr extends ServiceBase {

    constructor(protected http: Http, protected jsonp: Jsonp) { super(); }
    private currentType: string = "";
    /**
     * @param  {} userId 店长的用户Id
     */
    async getStore(id?): Promise<Store> {
        try {
            let url = "/api/stores/" + (id || this.LDCConfig.storeId);
            const res: any = await this.Get(url);
            this.CurrentStore = res;
            return res;
        } catch (error) {
            throw (error)
        }
    }
    async getKdsKitchens(storeId?: string) {
        const url = "/api/kitchensolutions?media=kds";
        return this.getOfFBS(url);
    }

    getKitchensolutions(ids?: Array<string>): Promise<Array<any>> {
        const queryStr = ids.join("&id=");
        return this.getOfFBS("/api/kitchensolutions?id=" + queryStr);
    }
    getKdsDevices(ids?: Array<string>): Promise<Array<Devices>> {
        return this.getOfFBS("/api/devices?deviceType=kds-printer")
    }

    mergeKdsDevices(id, devices) {
        return this.postOfFBS("/api/devices/" + id + "/merge", { devices })
    }
    unMergeKdsDevices(id, devices) {
        return this.postOfFBS("/api/devices/" + id + "/unmerge", { devices })
    }
    transferDevice(id, deviceId) {
        return this.postOfFBS("/api/devices/" + id + "/transfer", { transferOutId: deviceId })
    }
    cancelTransferDevice(id, deviceId) {
        return this.postOfFBS("/api/devices/" + id + "/cancelTransfer", { transferOutId: deviceId })
    }
    changeDeviceKitchenSolution(id, KitchenSolutionId) {
        return this.postOfFBS("/api/devices/" + id + "/changeKitchenSolutionId", { KitchenSolutionId })
    }
    async getLDCConfig(storeId?: string) {
        let url = "/api/stores/" + (storeId || this.LDCConfig.storeId) + "/config/get/config?type=system.ldc";
        let result: any = await this.Get(url);
        let ldcconfig = result;
        ldcconfig.ip = localstorageDao.get("preLDCs").find(x => x.storeId == storeId).ip;
        ldcconfig.storeId = this.LDCConfig.storeId;
        this.LDCConfig = ldcconfig;
        return this.LDCConfig;
    }

    getKitchenKieId(id) {
        const url = "/api/stores/" + this.CurrentStore.id + "/kitchens/" + id;
        return this.Get(url);
    }

    getCurrentDeviceId() {
        try {
            const url = this.adsAbout.url
            const ip = url.split("//")[1].split(":")[0];
            const ads_id = this.adsAbout.ads_id;
            const id = this.CurrentStore.id.substr(12) + ads_id.replace(/\:/g, '').toLowerCase() + "expedition";
            return id;
        } catch (error) {
            return "xx"
        }
    }
    async getDeviceKitchensolutions(id) {
        const devices = await this.getKdsDevices();
        const currentDevice = <any>devices.find(x => x.id == id);
        let kitchensolutions = [];
        if (currentDevice) {
            const deviceIds: Array<string> = currentDevice.transferIn || [];
            deviceIds.push(currentDevice.id);
            let ids = [];
            deviceIds.forEach(v => {
                const device = devices.find(x => x.id == v)
                device && ids.push(device.kitchenSolutionId)
            });
            kitchensolutions = await this.getKitchensolutions(ids);
            if (!Array.isArray(kitchensolutions)) {
                kitchensolutions = [kitchensolutions];
            }
        }
        return kitchensolutions;
    }
    async refreshLocalsotrage() {
        const id = await this.getCurrentDeviceId()
        const devices = await this.getKdsDevices();
        this.currentDevice = <any>devices.find(x => x.id == id);
        this.currentKitchenSolutions = await this.getDeviceKitchensolutions(id);
    }
    async getTerminalName() {
        let url = "/api/stores/" + this.CurrentStore.id + "/terminals/terminalname?boundApp=mkitchen";
        return this.GetCloud(url);
    }


    async getOtherDevices() {
        const devices = await this.getKdsDevices();
        const currentDeviceId = this.getCurrentDeviceId();
        const otherDevices = devices.filter(x => x.id != currentDeviceId);
        return otherDevices;
    }
    async getDeviceById(id) {
        const devices = await this.getKdsDevices();
        const currentDeviceId = this.getCurrentDeviceId();
        const device = devices.find(x => x.id == id);
        if (!device) throw new Error(`${currentDeviceId}没找到`)
        return device;
    }
    async bindKitchenDevice(kitchenSolutionId: string, deviceName: string) {
        const url = this.adsAbout.url
        const ip = url.split("//")[1].split(":")[0];
        const ads_id = this.adsAbout.ads_id;
        const id = this.getCurrentDeviceId();

        const deviceInfo: DeviceInfo = {
            "address": ip,
            "port": 9100,
            "extDeviceType": "kds-printer",
            "instructionSet": "kds/mpj"
        }
        const device: Device = {
            "type": "wifi",
            "address": ip, //本地地址
            "productName": ip,
            "manufacturer": ip,
            "deviceInfo": deviceInfo,
            "connectionType": "wifi"
        }
        const ads: Ads = {
            "retCode": 0,
            "version": "2.0",
            ads_id,
            "name": "kds-1",
            url, //本地地址
            "adapterIds": [
                ads_id
            ],
            "adsId": ads_id
        }
        const devices: Devices = {
            id,
            usage: "kds",
            instructionSet: "kds/mpj",
            ads,
            device,
            deviceInfo,
            kitchenSolutionId,
            storeId: this.CurrentStore.id,
            isShared: true,
            connectionType: "wifi",
            deviceType: "kds-printer",
            name: deviceName,
            deviceName: ip,
            state: "online"
        }
        try {
            const url = "/api/devices/" + devices.id;
            const result = await this.putOfFBS(url, devices);
            //存到localstorage
            localStorage.setItem("deviceId", result.currentDevice.id)
            this.currentDevice = result.currentDevice;
            return result;
        } catch (error) {
            throw error
        }
    }

    async cancelTerminal() {
        const terminal = this.Terminal;
        const url = "/api/stores/" + this.CurrentStore.id + "/terminals/" + terminal.id + "/unbound";
        return await this.PostCloud(url, terminal);
    }
    async deleteDevice(device) {
        const url = "/api/stores/" + this.CurrentStore.id + "/devices/" + device.id + "/delete";
        await this.putCloud(url, device);
    }

    async forbiddenDevice() {
        const device = this.currentDevice;
        device.isShared = false;
        const url = "/api/devices/" + device.id;
        const result = await this.putOfFBS(url, device);
        this.currentDevice = result.currentDevice;
    }

    async openDevice() {
        const device = this.currentDevice;
        device.isShared = true;
        const url = "/api/devices/" + device.id;
        const result = await this.putOfFBS(url, device);
        this.currentDevice = result.currentDevice;
    }

    async refreshDeviceForIp() {
        const url = this.adsAbout.url
        const ip = url.split("//")[1].split(":")[0];
        const ads_id = this.adsAbout.ads_id;
        const id = this.getCurrentDeviceId();

        const deviceInfo: DeviceInfo = {
            "address": ip,
            "port": 9100,
            "extDeviceType": "kds-printer",
            "instructionSet": "kds/mpj"
        }
        const deviceDevice: Device = {
            "type": "wifi",
            "address": ip, //本地地址
            "productName": ip,
            "manufacturer": ip,
            "deviceInfo": deviceInfo,
            "connectionType": "wifi"
        }
        const ads: Ads = {
            "retCode": 0,
            "version": "2.0",
            ads_id,
            "name": "kds-1",
            url, //本地地址
            "adapterIds": [
                ads_id
            ],
            "adsId": ads_id
        }
        try {
            const device = this.currentDevice;
            device.ads = ads;
            device.device = deviceDevice;
            device.deviceInfo = deviceInfo;
            device.deviceName = ip;
            const url = "/api/devices/" + device.id;
            const result = await this.putOfFBS(url, device);
            this.currentDevice = result.currentDevice;
            return result;
        } catch (error) {
            throw error
        }
    }

    
    //打印类型 wifi usb等
    setPrintType(type) {
        this.currentType = type;
    }

    getPrintType() {
        return this.currentType;
    }

    // 搜索到的设备
    private deviceData:any;
    setDeviceData(data){
        this.deviceData = data;
    }
    getDeviceData(){
        return this.deviceData;
    }

    // 打印机类型 出品打印机
    private deviceType:any;
    setDeviceType(deviceType){
        this.deviceType = deviceType;
    }
    getDeviceType(){
        return this.deviceType;
    }

    // wifi打印机地址
    private host:any;
    setHost(host){
        this.host = host;
    }
    getHost(){
        return this.host;
    }
}

interface Store {
    logoDisplay: string
}